const http = require('http');
const url = require('url');
const querystring = require('querystring');
const fs = require('fs');

let users = {};    // 暂存登录注册数据用

let server = http.createServer((request, response) => {
	// get
	let {pathname, query} = url.parse(request.url, true);
	// post
	let str = '';
	request.on('data', data => {
		str += data;
	});

	request.on('end', () => {
		let post = querystring.parse(str);
		// 所有东西要写在这里，在这里才能保证数据接收完了
		let {user, pwd} = query['user']?query:post;
		switch (pathname) {
			case '/reg':    // 注册
				if (!user) {
					response.write('{"err": "1", "msg": "必须填写用户名"}');
				} else if (!pwd) {
					response.write('{"err": "1", "msg": "必须填写密码"}');
				} else if (!/^\w{8,32}$/.test(user)) {
					response.write('{"err": "1", "msg": "用户名非法"}');
				} else if (/'|"/g.test(pwd)) {
					response.write('{"err": "1", "msg": "密码非法"}');
				} else if (users[user]) {
					response.write('{"err": "1", "msg": "用户名已被占用"}');
				} else {
					users[user] = pwd
					response.write('{"err": "0", "msg": "注册成功"}');
				}
				response.end();
				break;
			case '/login':     // 登录
				if (!user) {
					response.write('{"err": "1", "msg": "必须填写用户名"}');
				} else if (!pwd) {
					response.write('{"err": "1", "msg": "必须填写密码"}');
				} else if (!/^\w{8,32}$/.test(user)) {
					response.write('{"err": "1", "msg": "用户名非法"}');
				} else if (/'|"/g.test(pwd)) {
					response.write('{"err": "1", "msg": "密码非法"}');
				} else if (!users[user]) {
					response.write('{"err": "1", "msg": "用户不存在"}');
				} else if (users[user] != pwd) {
					response.write('{"err": "1", "msg": "用户名或密码错误"}');
				} else {
					response.write('{"err": "0", "msg": "登录成功"}');
				}
				response.end();
				break;
			default:       // 文件
				fs.readFile(`www${pathname}`, (err,data) => {
					if (err) {
						response.writeHead(404);
						response.write('Not Found');
					} else {
						response.write(data);
					}
					response.end();
				})
		}
	})
})

server.listen(8080);